const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());

app.all('*', (req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,POST');
    res.header('Access-Control-Allow-Headers', 'Content-Type,Authorization');
    next();
});

/**
 * 登录接口
 */
app.post('/login', (req, res) => {
    const {username, password } = req.body;
    if (username !== 'admin' || password !== 'admin') {
        res.status(400).json({
            msg: '用户名或密码错误'
        })
    }
    res.status(200).json({
        msg: 'ok',
        token: 'abc'
    })
})


// 获取数据接口（测试）
app.get('/list', (req, res) => {
    const token = req.headers['authorization'].split(' ')[1];
    console.log(">>>>>>>>>>>>>>>>>>>>> ", token);
    if (token === '' || token === undefined) {
        res.status(401).json({
            msg: '未登录'
        })
    }
    if (token !== 'abc') {
        res.status(401).json({
            msg: 'Token 无效'
        })
    }
    res.status(200).json({
        msg: 'ok',
        data: [1, 2, 3, 4]
    })
})


app.listen(8080, () => {
    console.log("ok");
})
